package com.crm.kz.common;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.content.FileProvider;

import java.io.File;

//将检查更新，下载apk，安装apk等操作封装成了一个类
public class AutoUpdater {
    // 下载安装包的网络路径
    private String apkUri = "http://10.0.2.2:8100/system/CheckVersion";

    // 保存APK的文件名
    private static final String saveFileName = "/app-release.apk";
    // 下载线程
    private Thread downLoadThread;

    // 应用程序Context
    private Context mContext;


    public static DownloadManager downloadManager;


    public AutoUpdater(Context context) {
        mContext = context;
    }


    //下载安装包
    public void DownloadApk() {
        downLoadThread = new Thread(DownApkWork);
        downLoadThread.start();
    }

    //下载线程任务
    private final Runnable DownApkWork = new Runnable() {
        @Override
        public void run() {
            //获取更新安装包的下载地址
            Uri uri = Uri.parse(apkUri);
            // 创建下载任务
            DownloadManager.Request request = new DownloadManager.Request(uri);
            //设置通知栏标题
            request.setVisibleInDownloadsUi(true);
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setTitle("手机安全卫士");
            request.setDescription("正在下载更新...");
            request.setMimeType("application/vnd.android.package-archive");
            //设置文件存放目录
            // 设置下载路径和下载的apk名称
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, saveFileName);
            Log.d("tag", Environment.DIRECTORY_DOWNLOADS + saveFileName);
            //获取系统服务
            downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
            // 将下载任务加入下载队列，并返回下载的id值
            long downloadId = downloadManager.enqueue(request);
            //将下载id存储到SharedPreferences中
            SharedPreferences sharedPreferences = mContext.getSharedPreferences("com.crm.kz.common.AutoUpdater", Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putLong("downloadId", downloadId);
            edit.apply();
        }
    };

    /**
     * 安装APK内容
     */
    //跳转安装 apk 需要适配不同的安卓版本，
    // Android 7.0 以上需要 “content://” 的路径
    // Android 6.0-7.0 需要老式的 “file://” 的路径，
    public void installAPK() {
        //获取内存中存储的下载id
        SharedPreferences sharedPreferences = mContext.getSharedPreferences("com.crm.kz.common.AutoUpdater", Context.MODE_PRIVATE);
        long downloadId = sharedPreferences.getLong("downloadId", -1L);

        //根据id查找apk的下载uri路径以安装
        Uri downloadUri = getDownloadUri(downloadId);
        //根据id查找apk的下载file://开头路径以安装
        File downloadFile = getDownloadFile(mContext, downloadId);
        try {
            if (!downloadFile.exists()) {
                Log.d("tag", "downloadFile路径：" + downloadFile.getAbsolutePath());
                Log.d("tag", "安装包不存在");
                return;
            }

            Log.d("tag", "正在安装");
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//安装完成后打开新版本
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // 给目标应用一个临时授权
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
                //如果SDK版本>24，即：Build.VERSION.SDK_INT > 24，使用FileProvider兼容安装apk

                Uri uri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileprovider", downloadFile);
                intent.setDataAndType(downloadUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(downloadFile), "application/vnd.android.package-archive");
            }
            mContext.startActivity(intent);
/*
            android.os.Process.killProcess(android.os.Process.myPid());//安装完之后会提示”完成” “打开”。
*/


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取下载安装包的保存地址
    public static Uri getDownloadUri(long downloadId) {
        return downloadManager.getUriForDownloadedFile(downloadId);
    }

    //根据下载id获取到 “file://” 的路径
    private static File getDownloadFile(Context context, long downloadId) {
        File targetApkFile = null;
        DownloadManager downloader = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);

        if (downloadId != -1L) {
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(downloadId);
            query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);

            Cursor cur = downloader.query(query);
            if (cur != null) {
                if (cur.moveToFirst()) {
                    @SuppressLint("Range") String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));

                    if (!TextUtils.isEmpty(uriString)) {
                        targetApkFile = new File(Uri.parse(uriString).getPath());
                    }
                }

                cur.close();
            }
        }

        return targetApkFile;
    }


}